<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Order extends CI_Controller {

	public function index()
	{

	}
	public function send()
	{
		$this->load->database();
		$this->log('Start ....');
		if(!isset($_POST['tourdayid']) || !isset($_POST['pricetype']) || !isset($_POST['client']))exit;
		$dsa=array();
		$this->log('Start .....'.$_POST['pricetype']);
		$tourDayId = (int)$_POST['tourdayid'];
		$dsa['tourId'] = $tourDayId;
		$this->log('Start .....'.$tourDayId);
		if($tourDayId == 0)exit;

		$aPriceTypes = array(1,2,3);
		if(!in_array($_POST['pricetype'], $aPriceTypes))exit;
		$priceType = $_POST['pricetype'];
		switch($priceType)
		{
			case 1: $priceType="SNGL";

				break;
			case 2: $priceType="DBL";

				break;
			case 3: $priceType="TRPL";

				break;

		}
		$dsa['priceType'] = $priceType;
		$clientId = (int)$_POST['client'];if($clientId == 0)exit;
		$dsa['userId'] = $clientId;
		$isDinner = (isset($_POST['dinner'])) ? (int)$_POST['dinner'] : 0;
		$isChild = (isset($_POST['child'])) ? (int)$_POST['child'] : 0;
		$hotel = (isset($_POST['hotel'])) ? (int)$_POST['hotel'] : 0; //надо ли хранить?
		
		$dsa['isChild'] = $isChild;
		$dsa['isDinner'] = $isDinner;
		
		if($hotel < 3 && $hotel > 5)$hotel = 3;

		$userName = (isset($_POST['user'])) ? htmlspecialchars($_POST['user']) : $_POST['user'];
		$email = (isset($_POST['email'])) ? htmlspecialchars($_POST['email']) : $_POST['email'];
		$phone = (isset($_POST['phone'])) ? htmlspecialchars($_POST['phone']) : $_POST['phone'];
		$wishes = (isset($_POST['wishes'])) ? htmlspecialchars($_POST['wishes']) : $_POST['wishes'];
		
		$dsa['FIO'] = $userName;
		$dsa['email'] = $email;
		$dsa['phone'] = $phone;
		$dsa['wishes'] = $wishes;
		
		$this->log("SELECT email FROM users WHERE id=".$clientId);
		$res =$this->db->query("SELECT email FROM users WHERE id=".$clientId);
		if($res->num_rows() > 0)
		{
			$this->log('after SELECT email');
			$row =$res->row();
			$clientEmail = $row->email;
		}
		else
		{
			exit;
		}
		$tourDateStart = '0000-00-00';
	$this->log($_POST['datestart']);
		if(isset($_POST['datestart']))
		{
		    if(preg_match('/^\d{4}\-\d{2}\-\d{2}$/',$_POST['datestart']) != 0)
		    {
		        $a = explode('-',$_POST['datestart']);
		        if(checkdate((int)$a[1], (int)$a[2], (int)$a[0])) {
					$tourDateStart = $_POST['datestart'];
				}
		    }
		}

		$dsa['dateStart'] = $tourDateStart;
		$query="Select tourTitle, nights,days from tours where id=".$tourDayId;
		$this->log($query);
		$result=$this->db->query($query);
		if($result->num_rows()>0)
		{
			$res=$result->row();
			$tourTitle=$res->tourTitle;
			$days=$res->days;
			$nights=$res->nights;
		}else exit;

		$childCol = ($isChild) ? ", CHLD" : "";
		$dinnerCol = ($isDinner) ? ", HB" : "";
		#$priceT='DBL';
		#if($priceType=='double')$priceT='DBL';
		#if($priceType=='single')$priceT='SNGL';
		#if($priceType=='triple')$priceT='TRPL';
		$query="SELECT $priceType as price $childCol $dinnerCol
				FROM  `prices`
				WHERE id = (
						SELECT price_id
						FROM dates
						WHERE DATE =  '$tourDateStart'
						AND TYPE =$hotel
						AND tour_id =$tourDayId
						LIMIT 1 ) ";
		$this->log($query);
		$result=$this->db->query($query);
		if($result->num_rows()>0)
		{
			$row=$result->row();
		}else exit;
	$this->log("SELECT");
		//calculating the total price
		$multiplier = 1;if($priceType == 'DBL')$multiplier = 2;elseif($priceType == 'TRPL')$multiplier = 3;
		$this->log($row->price);
		$priceTotal = $row->price * $multiplier;// * $rowTour['nights'];
		$this->log($priceTotal);
		if($isChild)$priceTotal += $row->CHLD;
		$this->log($priceTotal);
		if($isDinner)$priceTotal += $row->HB*$multiplier;
		$this->log($priceTotal);
		$dsa['totalPrice'] = $priceTotal;
		
		$isChild = ($isChild) ? 'Да' : 'Нет';
		$isDinner = ($isDinner) ? 'Да' : 'Нет';


		/// sending mail
		date_default_timezone_set('Europe/Kiev');
	//	require_once '/phpmailer/class.phpmailer.php';

		$this->load->model('orders');
		$this->orders->save_order($dsa);
		
		$bodyHTML = 'Заказ тура

		            Тур: '.$tourTitle.'
		            Дней: '.$days.'
		            Ночей: '.$nights.'
		            Дата заезда: '.$tourDateStart.'
		            Отель: '.$hotel.'*
		            Комната: '.$priceType.'
		            С ребенком: '.$isChild.'
		            С ужином: '.$isDinner.'
		            Общая сумма заказа: '.$priceTotal.'
					Дополнительные пожелания: '.$wishes.'
					Заказывающий:
		            Имя и фамилия: '.$userName.'
		            email: '.$email.'
		            телефон: '.$phone;

$this->log($bodyHTML);
		$this->load->library('email');

		$this->email->from('deliri9@gmail.com', 'RusTmarket.com');
		$this->email->to($clientEmail);

		$this->email->subject('Tour Order');
		$this->email->message($bodyHTML);

		$this->email->send();
	}
}